import { useEffect, type FC, } from 'react';
import { useMemoizedFn } from 'ahooks';
import { ImageBackground, View } from 'react-native';
import { useRouter, useNavigation } from 'expo-router';
import { LinearGradient } from 'expo-linear-gradient';
import { useBackHandler } from '@react-native-community/hooks';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import PageHeader from './header';
import { isIos } from '@/utils/helper';
import styles, { headerHeight } from './styles';
import type { PageWrapperProps } from './types';
import { useLoadingState } from '@/hooks/useLoadingState';

export const useHeight = () => {
  const { top } = useSafeAreaInsets();
  return [top + headerHeight];
}

const PageWrapper: FC<PageWrapperProps> = (props) => {
  const {
    hasSafeTop = false,
    lockBack = false,
    showHeader = true,
    linearGradient = false
  } = props;

  const router = useRouter();
  const navigate = useNavigation();
  const [safeHeight] = useHeight();
  const [loadingState] = useLoadingState();

  // 开始关闭 ios 手势
  const onGesture = useMemoizedFn(() => {
    if (!isIos()) return;

    let gestureEnabled = !lockBack;

    if (loadingState) {
      gestureEnabled = false;
    }

    navigate.setOptions({
      gestureEnabled
    });
  });

  const routerGoBack = useMemoizedFn(() => {
    if (router.canGoBack()) {
      router.back()
    }
  });

  const handleBack = useMemoizedFn(async () => {
    if (loadingState || lockBack) {
      return;
    }
    const back = await props.onBack?.()
    if (back ?? true) routerGoBack();
  });

  // 安卓 only
  useBackHandler(() => {
    handleBack();
    return true;
  });

  // ios only
  useEffect(onGesture, [
    lockBack,
    loadingState
  ]);

  return (
    <ImageBackground
      source={props.bgImage}
      style={styles.wrapper}
    >
      {showHeader && (
        <PageHeader
          {...props}
          onBack={handleBack}
        />
      )}
      {hasSafeTop && (
        <View
          style={{
            height: safeHeight
          }}
        />
      )}
      <LinearGradient
        style={styles.content}
        colors={linearGradient ?
          ['#5151C6', '#888BF4', '#fff'] :
          ['transparent', 'transparent']
        }
      >
        {props.children}
      </LinearGradient>
    </ImageBackground>
  );
}

export default PageWrapper;
